package com.azt.front.utils;

import com.azt.api.enums.LoginTypeEnum;
import com.azt.api.enums.RoleTypeEnum;
import com.azt.api.pojo.Company;
import com.azt.api.pojo.Role;
import com.azt.api.pojo.User;
import com.azt.api.service.UserService;
import com.azt.front.model.LoginCookie;
import com.azt.model.FrontGlobals;
import com.azt.utils.AESUtil;
import com.azt.utils.CommonUtil;
import com.azt.utils.CookieUtils;
import com.xiaoleilu.hutool.convert.Convert;
import com.xiaoleilu.hutool.date.DateField;
import com.xiaoleilu.hutool.date.DateUnit;
import com.xiaoleilu.hutool.date.DateUtil;
import com.xiaoleilu.hutool.util.ArrayUtil;
import com.xiaoleilu.hutool.util.CollectionUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

import static com.azt.front.utils.SpringContextUtil.getBean;


public class ContextUtil {

	/**
	 * SpringMvc下获取request
	 * 
	 * @return
	 */
	public static HttpServletRequest getRequest() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}

	public static HttpServletResponse getResponse() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
	}

	public static HttpSession getSession() {
		HttpSession session = getRequest().getSession();
		return session;

	}

	/**
	 * 获取当前登录用户
	 * */
	public static User getUser() {
		return UserContext.getUser();
	}

	/**
	 * 判断当前用户是否是管理员
	 * */
	public static boolean isAdmin() {
		List<Role> list = getRoles();
		Integer roleType = getCurrentRoleType();
		if(roleType != null && CollectionUtil.isNotEmpty(list)) {
			for (Role role : list) {
				if (role.getRoleType().intValue() == roleType.intValue() && role.getIfAdmin().intValue() == 1) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * 判断当前公司是否是分公司
	 * */
	public static boolean isSubCompany() {
		Company company = getCompany();
		return (company != null && company.getParentId() != null) ? true : false;
	}

	/**
	 * 获取当前用户的登录身份
	 * */
	public static Integer getCurrentRoleType() {
		Role role = getCurrentRole();
		return role != null ? role.getRoleType() : null;
	}

	/**
	 * 当前身份是否是采购商
	 * */
	public static boolean isPurchaser() {
		Integer roleType = getCurrentRoleType();
		return roleType != null && roleType.intValue() == RoleTypeEnum.PURCHASER.getValue();
	}

	/**
	 * 是否有采购商身份
	 * 有则返回该role
	 * Created by 张栋 on 2017/3/22 19:00
	 */
	public static Role  hasPurchaser(){
		List<Role> roles = getRoles();
		for (Role role : roles) {
			if( role!=null && role.getRoleType()!=null &&  role.getRoleType().intValue() ==RoleTypeEnum.PURCHASER.getValue()){
				return role;
			}
		}
		return null;
	}
	/**
	 * 是否有采购商身份
	 * Created by 张栋 on 2017/3/22 19:00
	 */
	public static Role  hasProvider(){
		List<Role> roles = getRoles();
		for (Role role : roles) {
			if( role!=null &&role.getRoleType()!=null &&  role.getRoleType().intValue() ==RoleTypeEnum.PROVIDER.getValue()){
				return role;
			}
		}
		return null;
	}


	/**
	 * 当前身份是否是供应商
	 * */
	public static boolean isProvider() {
		Integer roleType = getCurrentRoleType();
		return roleType != null && roleType.intValue() == RoleTypeEnum.PROVIDER.getValue();
	}

	/**
	 * 获取当前登录用户的id
	 * @return
	 */
	public static Integer getUserId(){
		User user = getUser();
		return user != null ? user.getId() : null;
	}

	public static void setUser(User user) {
		getSession().setAttribute(FrontGlobals.CURRENT_USER,
				getBean(UserService.class).getFullUserById(user.getId()));
	}

	/**
	 * 获取当前登录用户的所属公司
	 * */
	public static Company getCompany() {
		User user = getUser();
		return user != null ? user.getCompany() : null;
	}

	public static Integer getCompanyId() {
		Company company = getCompany();
		return company != null ? company.getId() : null;
	}

	/**
	 * 获取当前登陆用户的所有角色
	 */
	public static List<Role> getRoles() {
		User user = getUser();
		return user != null ? user.getRoles() : null;
	}

	/**
	 * @Description 判断图形验证码是否正确
	 * @param code 用户输入的值
	 * @return true 正确 false 不正确 
	 */
	public static boolean checkImageVerificationCode(String code){
		Object verCode = getSession().getAttribute(Globals.VALIDATE_IMAGE);
		if(verCode != null && verCode.toString().equalsIgnoreCase(code)){
			return true;
		}
		return false;
	}

	/**
	 * 获取当前用户的登录方式：用户名密码登录、记住我登录
	 * */
	public static Integer getLoginType() {
		return CommonUtil.safeToInteger(getSession().getAttribute(FrontGlobals.LOGIN_TYPE));
	}

	public static void setLoginType(Integer loginType) {
		getSession().setAttribute(FrontGlobals.LOGIN_TYPE, loginType);
	}

	/** 当前用户的登录身份 */
	public static Role getCurrentRole() {
		return (Role) getSession().getAttribute(FrontGlobals.CURRENT_ROLE);
	}

	public static void setCurrentRole(Role role) {
		getSession().setAttribute(FrontGlobals.CURRENT_ROLE, role);
	}

	/**
	 * 当前用户是否经过身份验证登录（即通过密码登录的，而不是通过记住我登录的）
	 * */
	public static boolean isAuthenticated() {
		User user = getUser();
		Integer loginType = getLoginType();
		if(user != null && loginType != null && loginType.intValue() == LoginTypeEnum.AUTH.getValue()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 当前用户是否是通过记住我登录的
	 * */
	public static boolean isRemembered() {
		User user = getUser();
		Integer loginType = getLoginType();
		if(user != null && loginType != null && loginType.intValue() == LoginTypeEnum.REMEMBERME.getValue()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 当前用户是否已经登录（通过密码登录或者记住我登录）
	 * */
	public static boolean isLogined() {
		return isAuthenticated() || isRemembered();
	}

	public static void setCommonLoginCookie(Integer userId, String username, Integer currentRoleId, String salt) {
        LoginCookie cookie = new LoginCookie(userId, username, currentRoleId,
                salt, new Date(), new Date());
        setLoginCookie(cookie);
    }

    public static void setRememberMeLoginCookie(Integer userId, String username, Integer currentRoleId, String salt) {
        LoginCookie cookie = new LoginCookie(userId, username, currentRoleId,
                salt, new Date(), DateUtil.offset(new Date(), DateField.SECOND, FrontGlobals.REMEMBERME_COOKIE_EXPIRE));
        setLoginCookie(cookie);
    }

	/**
	 * 设置登录cookie
	 * */
	public static void setLoginCookie(LoginCookie cookie) {
		//cookie内容：userId|username|currentRoleId|salt|登录时间|过期时间
		String src = StrUtil.format("{}|{}|{}|{}|{}|{}",
				cookie.getUserId(), cookie.getUsername(), cookie.getCurrentRoleId(), cookie.getSalt(),
				cookie.getLoginTime().getTime(), cookie.getExpireTime().getTime());
		String cookieValue = AESUtil.encrypt(src, FrontGlobals.LOGIN_COOKIE_KEY);
//		LOGGER.info("login cookie:" + cookieValue);
        long maxAge = DateUtil.between(cookie.getLoginTime(), cookie.getExpireTime(), DateUnit.SECOND);
		CookieUtils.setHttpOnlyCookie(getRequest(), getResponse(), FrontGlobals.LOGIN_COOKIE_NAME, cookieValue, maxAge > 0 ? Convert.toInt(maxAge) : -1);
	}

	/**
	 * 获取登录cookie
	 * */
	public static LoginCookie getLoginCookie() {
		String cookieValue = CookieUtils.getCookieValue(getRequest(), FrontGlobals.LOGIN_COOKIE_NAME);
		if (StringUtils.isNotBlank(cookieValue)) {
			String str = AESUtil.decrypt(cookieValue, FrontGlobals.LOGIN_COOKIE_KEY);
			if (StringUtils.isNotBlank(str)) {
				//格式 uid|username|currentRoleId|salt|上次登录时间|过期时间
				String[] array = str.split("\\|");
				if (array.length == 6) {
					Integer uid = Convert.toInt(array[0]);
					String username = array[1];
					Integer currentRoleId = Convert.toInt(array[2]);
					String salt = array[3];
					Long loginTimeMillis = Convert.toLong(array[4]);
                    Long expireTimeMillis = Convert.toLong(array[5]);
					if (uid != null && currentRoleId != null && loginTimeMillis != null && expireTimeMillis != null
                            && StringUtils.isNoneBlank(username, salt)) {
						Date expireTime = DateUtil.date(expireTimeMillis);
						if(expireTime.after(new Date())) {
							return new LoginCookie(uid, username, currentRoleId, salt, DateUtil.date(loginTimeMillis), expireTime);
						}
					}
				}
			}
		}
		return null;
	}

	/**
	 * 获取购物车
	 * */
	public static List<Map> getCartCookie() {
		List<Map> cartList = new ArrayList<>();

		//购物车cookie，格式：skuId-quantity, ...
		String cartValue = CookieUtils.getCookieValue(getRequest(), Globals.CART_COOKIE, true);

		if(StrUtil.isNotBlank(cartValue)) {
			String[] array = cartValue.split("\\,");
			for (String s : array) {
				try {
					String[] _array = s.split("\\-");
					if (ArrayUtil.isEmpty(_array) || _array.length != 2) {
						continue;
					}
					Integer skuId = Convert.toInt(_array[0]);
					Integer quantity = Convert.toInt(_array[1]);
					if (skuId != null && quantity != null) {
						Map m = new HashMap();
						m.put("skuId", skuId);
						m.put("quantity", quantity);
						cartList.add(m);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return cartList;
	}

	public static void setCartCookie(List<Map> cartList) {
		if(cartList != null && cartList.size() > 0) {
			StringBuilder cartValue = new StringBuilder();
			for(Map cart : cartList) {
				Integer skuId = Convert.toInt(cart.get("skuId"));
				Integer quantity = Convert.toInt(cart.get("quantity"));
				if(skuId != null && quantity != null) {
					cartValue.append(skuId).append("-").append(quantity).append(",");
				}
			}
			if(cartValue.toString().endsWith(",")) {
				cartValue = cartValue.deleteCharAt(cartValue.length() - 1);
			}
			if(cartValue == null || cartValue.length() == 0) {
				CookieUtils.deleteCookie(getRequest(), getResponse(), Globals.CART_COOKIE);
			} else {
				CookieUtils.setCookie(getRequest(), getResponse(), Globals.CART_COOKIE, cartValue.toString(), 365 * 24 * 60 * 60, true);
			}
		} else {
			CookieUtils.deleteCookie(getRequest(), getResponse(), Globals.CART_COOKIE);
		}
	}
}
